/* Copyright (c) 2012 Michele Roohani, Frank Harper, Pierre Gros, Pierre LEVY
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.aocfrance.app.ui.fragment;

import java.io.InputStream;
import java.net.URL;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;

import com.aocfrance.app.Constants;
import com.aocfrance.app.R;
import com.aocfrance.app.model.Producteur;
import com.aocfrance.app.service.ProducteurService;


/**
 *
 * @author pierre
 */
public class ProducteurDetailFragment extends Fragment
{

	Producteur mProducteur;
	View v;

	/**
	 * {@inheritDoc }
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState)
	{

		v = inflater.inflate(R.layout.producteur_detail, container, false);


		return v;
	}

	public void updateProducteur(int mProducteurId)
	{
		new LoadProducteurTask().execute( mProducteurId );
	}

	public void clearUI() {
		ImageView mIvPhoto = (ImageView) v.findViewById(R.id.photo_producteur);
		ProgressBar mPb = (ProgressBar)v.findViewById(R.id.photo_producteur_progressBar);
		mPb.setVisibility(View.VISIBLE);
		mIvPhoto.setVisibility(View.GONE);

		TextView mTvName = (TextView) v.findViewById(R.id.name_producteur);
		mTvName.setText(R.string.producteur_titre);

		TextView mTvAdresse = (TextView) v.findViewById(R.id.adresse_producteur);
		mTvAdresse.setText(R.string.producteur_adresse);

		TextView mTvPresentation = (TextView) v.findViewById(R.id.presentation_producteur);
		mTvPresentation.setText(mProducteur.getPresentation());

		RatingBar mRbRating = (RatingBar)v.findViewById(R.id.ratingBarDisplay);
		mRbRating.setRating(0);
		mRbRating.setOnTouchListener(null);
	}

	public void updateUI()
	{
		clearUI();
		LinearLayout mLlDetails = (LinearLayout) v.findViewById(R.id.donnes_producteur);
		mLlDetails.setVisibility(View.VISIBLE);
		LinearLayout mLlDetailsVide = (LinearLayout) v.findViewById(R.id.donnes_producteur_absentes);
		mLlDetailsVide.setVisibility(View.GONE);

		if(mProducteur != null) {
			TextView mTvName = (TextView) v.findViewById(R.id.name_producteur);
			mTvName.setText(mProducteur.getNom());

			TextView mTvAdresse = (TextView) v.findViewById(R.id.adresse_producteur);
			mTvAdresse.setText(mProducteur.getAdresse());

			TextView mTvPresentation = (TextView) v.findViewById(R.id.presentation_producteur);
			mTvPresentation.setText(mProducteur.getPresentation());

			RatingBar mRbRating = (RatingBar)v.findViewById(R.id.ratingBarDisplay);
			float rating = (float)mProducteur.getRating();
			mRbRating.setRating(rating);

			String photoUrl = mProducteur.getPhoto();
			//if(photoUrl != null && !photoUrl.equals("") && !photoUrl.equals("null")) {
			new LoadProducteurPictureTask().execute( photoUrl );
			//}
			mRbRating.setOnTouchListener(new OnTouchListener() {

				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					//showDialog(mProducteur.getResource_uri(), mProducteur.getRating());
					return false;
				}
			});

		}
	}
	private void updatePicture(Bitmap bitmap) {
		ImageView mIvPhoto = (ImageView) v.findViewById(R.id.photo_producteur);
		ProgressBar mPb = (ProgressBar)v.findViewById(R.id.photo_producteur_progressBar);
		if(bitmap != null)
			mIvPhoto.setImageBitmap(bitmap);
		else
			mIvPhoto.setImageResource(R.drawable.about_pressed);

		mPb.setVisibility(View.GONE);
		mIvPhoto.setVisibility(View.VISIBLE);
	}
	private class LoadProducteurTask extends AsyncTask<Integer, Void, Void>
	{

		@Override
		protected Void doInBackground(Integer... arg)
		{
			mProducteur = ProducteurService.loadProducteur( arg[0] );
			return null;
		}

		@Override
		protected void onPostExecute(Void result)
		{
			updateUI();
		}
	}
	private class LoadProducteurPictureTask extends AsyncTask<String, Void, Bitmap>
	{

		@Override
		protected Bitmap doInBackground(String... url)
		{
			Bitmap bitmap = null;
			try {
				bitmap = BitmapFactory.decodeStream((InputStream)new URL(url[0]).getContent());
			} catch (Exception e) {	}
			return bitmap;
		}

		@Override
		protected void onPostExecute(Bitmap result)
		{
			updatePicture(result);
		}
	}









	void showDialog(String resource_uri, double rating) {
		DialogFragment newFragment = MyAlertDialogFragment.newInstance(
				R.string.alert_dialog_title, resource_uri, rating);
		newFragment.show(getFragmentManager(), "dialog");
	}

	public static class MyAlertDialogFragment extends DialogFragment {

		public static MyAlertDialogFragment newInstance(int title, String resource_uri, double rating) {
			MyAlertDialogFragment frag = new MyAlertDialogFragment();
			Bundle args = new Bundle();
			args.putInt("title", title);
			args.putString("resource_uri", resource_uri);
			args.putDouble("rating", rating);
			frag.setArguments(args);
			return frag;
		}
		/*public MyAlertDialogFragment(int title, String resource_uri, double rating) {
			Bundle args = new Bundle();
			args.putInt("title", title);
			args.putString("resource_uri", resource_uri);
			args.putDouble("rating", rating);
			this.setArguments(args);
		}*/
		
		private static double currentVote = 0;
		protected static void vote(String resource_uri) {
			Log.d(Constants.TAG, "Vote pour "+resource_uri+" = "+currentVote);
			new VoteProducteursTask().execute(new Object[]{resource_uri,new Double(currentVote)});
		}
		protected static void setVote(double rating) {
			currentVote = rating;
		}
		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			int title = getArguments().getInt("title");
			//String resource_uri = getArguments().getString("resource_uri");
			double rating = getArguments().getDouble("rating");

			LayoutInflater inflater = getActivity().getLayoutInflater();
			View view = inflater.inflate(R.layout.rate, null);

			RatingBar mRbRating = (RatingBar)view.findViewById(R.id.ratingBarRate);
			mRbRating.setRating((float)rating);
			setVote(rating);
			mRbRating.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener(){

				public void onRatingChanged(RatingBar ratingBar, float rating,
						boolean fromUser) {
					setVote(ratingBar.getRating());
					
				}});

			Builder b = new AlertDialog.Builder(getActivity())
			.setIcon(R.drawable.ic_launcher)
			.setTitle(title)
			.setView(view)
			.setPositiveButton(R.string.alert_dialog_ok,
					new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					vote(getArguments().getString("resource_uri"));
				}
			}
					)
					.setNegativeButton(R.string.alert_dialog_cancel,
							new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							//((FragmentAlertDialog)getActivity()).doNegativeClick();
						}
					}
							);
			
			Dialog dialog = b.create();
			return dialog;
		}
		
		private static class VoteProducteursTask extends AsyncTask<Object, Void, Boolean>
	    {

	        @Override
	        protected Boolean doInBackground(Object... arg0)
	        {
	            return  ProducteurService.vote((String)arg0[0], (Double)arg0[1]);
	        }

	        @Override
	        protected void onPostExecute(Boolean result)
	        {
	        	Log.d(Constants.TAG,"Vote effectué : "+(result?"oui":"non"));
	        }
	    }
	}

}